<template>
  <div>
    <h3>拖拽文件上传</h3>
    <!-- 
      拖拽事件：dragenter dragleave dragover drop
    -->
    <div
      class="upload_div"
      :class="[{ dragover: dragoverStyle }]"
      @dragenter="dragenter"
      @dragover="dragover"
      @dragleave="dragleave"
      @drop="drop"
    >
      <div class="modalDiv" v-show="modalDivVisable">
        文件正在上传中
      </div>
      <input
        ref="fileInput"
        type="file"
        class="fileInput"
        @change="changeFile"
      />
      <div class="upload_box">
        拖动文件至此上传或
        <button @click="chooseFile" class="button select">
          选择文件
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadSingleFile } from "@/api/upload/SingleUploader.js";

export default {
  data() {
    return {
      file: null,
      dragoverStyle: false,
      modalDivVisable: false,
      isRun: false, // 防抖
    };
  },
  methods: {
    chooseFile() {
      this.$refs.fileInput.click();
    },
    changeFile() {
      let file = this.$refs.fileInput.files[0];
      this.file = file;
      this.uploadFile();
    },
    dragenter() {
      this.dragoverStyle = true;
    },
    dragover(event) {
      // 阻止默认行为
      event.preventDefault();
    },
    dragleave() {
      this.dragoverStyle = false;
    },
    drop(event) {
      console.log("drop");
      // 阻止默认行为（浏览器默认会打开拖拽进浏览器的文件）
      event.preventDefault();
      let file = event.dataTransfer.files[0];
      if (!file) return;

      this.file = file;
      this.dragoverStyle = false;
      this.uploadFile();
    },
    uploadFile() {
      if (this.isRun) return;
      if (!this.file) return;

      let formData = new FormData();
      formData.append("file", this.file);

      this.isRun = true;
      this.modalDivVisable = true;
      uploadSingleFile(formData)
        .then((data) => {
          if (data.code == 200) {
            this.$message({
              type: "success",
              message: "上传文件成功：" + data.data,
            });
            this.file = null;
            return;
          }
          this.$message({
            type: "error",
            message: "上传文件失败：" + data.msg,
          });
        })
        .finally(() => {
          this.isRun = false;
          this.modalDivVisable = false;
        });
    },
  },
};
</script>

<style scoped>
.upload_div {
  width: 400px;
  height: 150px;
  border: #ccc dashed 1px;
  margin: auto;
  font-size: 12px;
}
.modalDiv {
  width: 400px;
  height: 150px;
  background-color: rgba(200, 200, 200, 0.5);
  position: absolute;
  line-height: 150px;
  font-weight: bold;
}
.upload_div.dragover {
  background-color: #00b9f1;
}
.upload_div.dragover::after {
  content: "释放鼠标上传文件";
}
.fileInput {
  display: none;
}
.button.select {
  margin: 5px;
  padding: 5px;
  border: #ccc 1px outset;
  border-radius: 5px;
  background-color: #00b9f1;
}
.button.select:active {
  border: #ccc 1px inset;
}
</style>